using System;
using System.IO;
using System.Windows;
using System.Windows.Input;

namespace GameOverlayWPF
{
    public partial class SettingsWindow : Window
    {
        private HotkeyRecorder? _hotkeyRecorder;
        private HotkeyRecorder? _audioHotkeyRecorder;
        private HotkeySettings _settings;
        private MainWindow? _mainWindow;
        public bool HotkeyChanged { get; private set; } = false;
        public bool AudioHotkeyChanged { get; private set; } = false;
        public bool OpacityChanged { get; private set; } = false;

        public SettingsWindow()
        {
            InitializeComponent();
            _settings = HotkeySettings.Instance;
            
            // 使用 Loaded 事件确保所有控件完全初始化后再加载设置
            this.Loaded += SettingsWindow_Loaded;
        }

        private void SettingsWindow_Loaded(object sender, RoutedEventArgs e)
        {
            LoadSettings();
        }

        private void LoadSettings()
        {
            // 显示当前热键
            HotkeyTextBox.Text = _settings.HotkeyText;
            AudioHotkeyTextBox.Text = _settings.AudioHotkeyText;
            
            // 获取主窗口引用
            _mainWindow = Owner as MainWindow;
            
            System.Diagnostics.Debug.WriteLine($"[SettingsWindow] LoadSettings: _mainWindow = {_mainWindow != null}");
            System.Diagnostics.Debug.WriteLine($"[SettingsWindow] LoadSettings: OpacitySlider = {OpacitySlider != null}");
            System.Diagnostics.Debug.WriteLine($"[SettingsWindow] LoadSettings: WindowOpacity = {_settings.WindowOpacity}");
            
            // 加载透明度设置（暂时禁用 ValueChanged 事件以避免循环触发）
            if (_mainWindow != null && OpacitySlider != null)
            {
                OpacitySlider.ValueChanged -= OpacitySlider_ValueChanged;
                OpacitySlider.Value = _settings.WindowOpacity * 100;
                OpacityValueText.Text = $"{(int)OpacitySlider.Value}%";
                OpacitySlider.ValueChanged += OpacitySlider_ValueChanged;
                
                System.Diagnostics.Debug.WriteLine($"[SettingsWindow] 透明度已加载: {OpacitySlider.Value}%");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"[SettingsWindow] 警告：无法加载透明度设置 - MainWindow={_mainWindow != null}, Slider={OpacitySlider != null}");
            }
        }

        private void CloseSettingsBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void SetHotkeyBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 创建热键录制器
                if (_hotkeyRecorder == null)
                {
                    _hotkeyRecorder = new HotkeyRecorder(HotkeyTextBox);
                    _hotkeyRecorder.HotkeyRecorded += HotkeyRecorder_HotkeyRecorded;
                }

                // 开始录制
                _hotkeyRecorder.StartRecording();
                SetHotkeyBtn.IsEnabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动热键录制失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void HotkeyRecorder_HotkeyRecorded(object? sender, HotkeyRecordedEventArgs e)
        {
            try
            {
                // 更新设置
                _settings.Modifiers = e.Modifiers;
                _settings.MainKey = e.MainKey;

                // 显示新热键
                HotkeyTextBox.Text = _settings.HotkeyText;

                // 标记热键已更改
                HotkeyChanged = true;

                // 恢复按钮状态
                SetHotkeyBtn.IsEnabled = true;

                MessageBox.Show(
                    $"热键已设置为：{_settings.HotkeyText}\n\n点击【确定】保存更改。",
                    "热键设置",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information
                );
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存热键失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                SetHotkeyBtn.IsEnabled = true;
            }
        }

        private void SetAudioHotkeyBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 创建音频热键录制器
                if (_audioHotkeyRecorder == null)
                {
                    _audioHotkeyRecorder = new HotkeyRecorder(AudioHotkeyTextBox);
                    _audioHotkeyRecorder.HotkeyRecorded += AudioHotkeyRecorder_HotkeyRecorded;
                }

                // 开始录制
                _audioHotkeyRecorder.StartRecording();
                SetAudioHotkeyBtn.IsEnabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动音频热键录制失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void AudioHotkeyRecorder_HotkeyRecorded(object? sender, HotkeyRecordedEventArgs e)
        {
            try
            {
                // 更新设置
                _settings.AudioModifiers = e.Modifiers;
                _settings.AudioMainKey = e.MainKey;

                // 显示新热键
                AudioHotkeyTextBox.Text = _settings.AudioHotkeyText;

                // 标记音频热键已更改
                AudioHotkeyChanged = true;

                // 恢复按钮状态
                SetAudioHotkeyBtn.IsEnabled = true;

                MessageBox.Show(
                    $"音频热键已设置为：{_settings.AudioHotkeyText}\n\n点击【确定】保存更改。",
                    "音频热键设置",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information
                );
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存音频热键失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                SetAudioHotkeyBtn.IsEnabled = true;
            }
        }

        private void TestAudioBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string audioFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "11.mp3");
                System.Diagnostics.Debug.WriteLine("=== 测试音频播放按钮点击 ===");
                
                var audioService = AudioService.Instance;
                audioService.TestPlay(audioFilePath);
                
                // 显示测试提示
                MessageBox.Show(
                    "音频测试播放已启动！\n\n请查看调试输出窗口了解详细信息。",
                    "音频测试",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information
                );
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"测试音频播放失败: {ex.Message}");
                MessageBox.Show(
                    $"测试音频播放失败：\n{ex.Message}",
                    "错误",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error
                );
            }
        }

        private void OpacitySlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            System.Diagnostics.Debug.WriteLine($"[OpacitySlider] ValueChanged: Old={e.OldValue}, New={e.NewValue}");
            System.Diagnostics.Debug.WriteLine($"[OpacitySlider] OpacityValueText={OpacityValueText != null}, MainWindow={_mainWindow != null}");
            
            if (OpacityValueText == null || _mainWindow == null)
            {
                System.Diagnostics.Debug.WriteLine("[OpacitySlider] 跳过：控件未初始化");
                return;
            }
            
            // 更新显示文本
            OpacityValueText.Text = $"{(int)OpacitySlider.Value}%";
            
            // 实时预览透明度效果
            double opacity = OpacitySlider.Value / 100.0;
            _mainWindow.Opacity = opacity;
            System.Diagnostics.Debug.WriteLine($"[OpacitySlider] 主窗口透明度已设置为: {opacity} ({OpacitySlider.Value}%)");
            
            // 标记透明度已更改
            OpacityChanged = true;
        }

        private void OKBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bool hasChanges = false;
                
                if (HotkeyChanged)
                {
                    // 保存热键设置
                    hasChanges = true;
                }
                
                if (AudioHotkeyChanged)
                {
                    // 保存音频热键设置
                    hasChanges = true;
                }
                
                if (OpacityChanged)
                {
                    // 保存透明度设置
                    _settings.WindowOpacity = OpacitySlider.Value / 100.0;
                    hasChanges = true;
                }
                
                if (hasChanges)
                {
                    // 保存所有设置
                    _settings.Save();
                    
                    string message = "设置已保存！";
                    if (HotkeyChanged || AudioHotkeyChanged)
                    {
                        message += "\n\n新热键将在重启应用后生效。";
                    }
                    if (OpacityChanged)
                    {
                        message += "\n透明度已立即生效。";
                    }
                    
                    MessageBox.Show(
                        message,
                        "提示",
                        MessageBoxButton.OK,
                        MessageBoxImage.Information
                    );
                }

                this.DialogResult = true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            
            // 取消订阅 Loaded 事件，防止内存泄漏
            this.Loaded -= SettingsWindow_Loaded;
            
            // 清理热键录制器资源
            if (_hotkeyRecorder != null)
            {
                _hotkeyRecorder.HotkeyRecorded -= HotkeyRecorder_HotkeyRecorded;
                _hotkeyRecorder.Dispose();
                _hotkeyRecorder = null;
            }
            
            // 清理音频热键录制器资源
            if (_audioHotkeyRecorder != null)
            {
                _audioHotkeyRecorder.HotkeyRecorded -= AudioHotkeyRecorder_HotkeyRecorded;
                _audioHotkeyRecorder.Dispose();
                _audioHotkeyRecorder = null;
            }
            
            // 清理主窗口引用
            _mainWindow = null;
        }
    }
}



